package com.keshihao.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.keshihao.commonutils.R;
import com.keshihao.servicebase.exceptionhandler.TechException;
import com.keshihao.vod.service.VodService;
import com.keshihao.vod.utils.ConstantVodUtils;
import com.keshihao.vod.utils.InitVodClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @Author Mr.Keshihao
 * @Date 2020/6/12 15:55
 * @Version 1.0
 */
@CrossOrigin
@RestController
@RequestMapping("/eduvod/video")
public class VodController {

  @Autowired
  private VodService vodService;

  // 上传视频到阿里云视频点播平台
  @PostMapping("/uploadAliyVideo")
  public R uploadAliyVideo(MultipartFile file) {

    // 返回上传视频id
    String videoId = vodService.uploadVideoAly(file);

    return R.ok().data("videoId",videoId);
  }

  // 根据视频id删除阿里云视频
  @DeleteMapping("/removeAlyVideo/{id}")
  public R removeAlyVideo(@PathVariable String id) {

    try {
      // 初始化阿里云对象
      DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.KEY_ID, ConstantVodUtils.KEY_SECRET);
      // 创建删除视频的request对象
      DeleteVideoRequest request = new DeleteVideoRequest();
      // 向request设置视频id
      request.setVideoIds(id);
      // 调用初始化对象中的方法实现删除视频
      client.getAcsResponse(request);
      return R.ok();

    } catch (Exception e) {
      e.printStackTrace();
      throw new TechException(20001,"删除视频失败");
    }


  }

  // 删除多个阿里云中的视频
  @DeleteMapping("/removeAlyVideos")
  public R removeAlyVideos(@RequestParam("videoIdList") List<String> videoIdList) {

    try {
      // 初始化阿里云对象
      DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.KEY_ID, ConstantVodUtils.KEY_SECRET);
      // 创建删除视频的request对象
      DeleteVideoRequest request = new DeleteVideoRequest();
      // 将List中数据格式化成指定格式
      String videoIds = StringUtils.join(videoIdList.toArray(), ",");
      // 向request设置视频id
      request.setVideoIds(videoIds);
      // 调用初始化对象中的方法实现删除视频
      client.getAcsResponse(request);
      return R.ok();

    } catch (Exception e) {
      e.printStackTrace();
      throw new TechException(20001,"删除视频失败");
    }


  }

}
